package com.shuyuntu.proposal.controller;

import com.shuyuntu.proposal.entity.Article;
import com.shuyuntu.proposal.entity.Attachment;
import com.shuyuntu.proposal.entity.Department;
import com.shuyuntu.proposal.entity.Proposal;
import com.shuyuntu.proposal.enums.EArticleType;
import com.shuyuntu.proposal.enums.EProposalState;
import com.shuyuntu.proposal.enums.EProposalType;
import com.shuyuntu.proposal.service.ArticleService;
import com.shuyuntu.proposal.service.DelegateService;
import com.shuyuntu.proposal.vo.PostedProposalVO;
import org.hibernate.exception.SQLGrammarException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 其他文章的控制器
 * Created by limeng on 16/8/22.
 */
@Controller
@RequestMapping("/article")
public class ArticleController {
    /*============= injection ==============*/
    @Resource
    private ArticleService articleService;
    @Resource
    private DelegateService delegateService;

    public ArticleService getArticleService() {
        return articleService;
    }

    public void setArticleService(ArticleService articleService) {
        this.articleService = articleService;
    }

    public DelegateService getDelegateService() {
        return delegateService;
    }

    public void setDelegateService(DelegateService delegateService) {
        this.delegateService = delegateService;
    }
    /*============= injection ==============*/

    /**
     * 将提案保存到服务器
     * @param session       注入的session实例
     * @return  上传成功与否的json对象
     */
    @ResponseBody
    @RequestMapping(value = "/", method = RequestMethod.POST)
    public Map<String, Object> postNewArticle(
            @RequestBody Map<String, Object> postedArticle, HttpSession session) {
        Map<String, Object> resultMap = new LinkedHashMap<>();

        //字段合法性检查
        if (postedArticle.get("title") == null || postedArticle.get("title").equals("")) {
            resultMap.put("state", false);
            resultMap.put("result", "标题不允许为空");
            return resultMap;
        }
        //检查是不是当前用户写的
        if (session.getAttribute("loginUserId").equals(postedArticle.get("authorId"))) {
            Article article = new Article();

            article.setTitle((String) postedArticle.get("title"));
            article.setContent((String) postedArticle.get("content"));
            try {
                article.setAuthor(
                        delegateService.getDelegateById((String) postedArticle.get("authorId")));
            } catch (Exception e) {
                e.printStackTrace();
                resultMap.put("state", false);
                resultMap.put("result", "监测到非法数据");

                return resultMap;
            }

            Date date = new Date();
            article.setCreateTime(date);
            article.setUpdateTime(date);

            
            article.setType(EArticleType.values()[(Integer)postedArticle.get("type")]);
            article.setClickCount(0);
            
            //插入数据
            if (articleService.publishArticle(article)) {
                resultMap.put("state", true);
            } else {
                resultMap.put("state", false);
                resultMap.put("result", "数据库出现异常,请联系维护人员");
            }
        } else {
            resultMap.put("state", false);
            resultMap.put("result", "您的身份验证失败！");
        }

        return resultMap;
    }

    /**
     * 更新一个提案
     * @param reqMap 请求jsonMap
     * @param session injection
     * @param response injection
     * @return jsonMap
     */
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Map<String, Object> updateArticle(@RequestBody Map<String, Object> reqMap,
                                              HttpSession session,
                                              HttpServletResponse response) {
        Integer articlelId = Integer.parseInt((String)reqMap.get("id"));
        Map<String, Object> resMap = new LinkedHashMap<>();

        Article article = articleService.getArticleById(articlelId);
        if (article == null) {
            resMap.put("state", false);
            resMap.put("result", "找不到指定的文章");
            return resMap;
        }

        String authorId = (String)session.getAttribute("loginUserId");
        if (authorId != null && authorId.equals(article.getAuthor().getId())) {
            String title = (String) reqMap.get("title");
            String content = (String) reqMap.get("content");

            EArticleType articleType = null;

            try {
                Integer type = (Integer)reqMap.get("type");
                if (type != null)
                    articleType = EArticleType.values()[type];
            } catch (ClassCastException e) {
                String typeStr = (String)reqMap.get("type");
                if (typeStr != null) {
                    Integer type = Integer.parseInt(typeStr);
                    articleType = EArticleType.values()[type];
                }
            }

            if (title != null && !title.equals("")) {
                article.setTitle(title);
            }
            article.setContent(content);
            article.setUpdateTime(new Date());
            article.setType(articleType);
            
            if (articleService.updateArticle(article)) {
                resMap.put("state", true);
            } else {
                resMap.put("state", false);
                resMap.put("result", "数据库异常!");
            }
            return resMap;
        }

        response.setStatus(404);
        resMap.put("state", false);
        resMap.put("result", "权限不足!");
        return resMap;
    }

    /**
     * 删除一个提案
     * @param session injection
     * @return state json
     */
    @ResponseBody
    @RequestMapping(value = "/{articleId}", method = RequestMethod.DELETE)
    public Map<String, Object> deleteArticle(
            @PathVariable int articleId,
            HttpSession session) {
        Article article = articleService.getArticleById(articleId);
        String authorId = (String)session.getAttribute("loginUserId");
        Map<String, Object> resMap = new LinkedHashMap<>();
        if (authorId != null && authorId.equals(article.getAuthor().getId())) {
            if (articleService.deleteArticle(article)) {
                resMap.put("state", true);
            } else {
                resMap.put("state", false);
                resMap.put("result", "数据库异常!");
            }
            return resMap;
        }
        resMap.put("state", false);
        resMap.put("result", "权限认证失败!");
        return resMap;
    }

    /**
     * 根据指定的条件,返回查询得到的提案列表
     * @param reqMap 请求集合
     *        pageSize : 分页大小
     *        pageNo : 分页页数
     *        authorId : 作者id
     *        type : 提案类型
     * @return
     *        state:true/false,
     *        list : [提案列表],
     *        pageCount : 总页数
     */
    @ResponseBody
    @RequestMapping("/search")
    public Map<String ,Object> searchArticle(
            @RequestBody Map<String, Object> reqMap) {
        Integer pageSize = (Integer)reqMap.get("pageSize");
        Integer pageNo = (Integer)reqMap.get("pageNo");

        Map<String, Object> resMap = new LinkedHashMap<>();
        StringBuffer rowCount = new StringBuffer();
        try {
            List<Article> list = articleService.doSearch(pageSize, pageNo, reqMap, rowCount);

            resMap.put("state", true);
            resMap.put("list", list);
            Integer pageCount = (Integer.parseInt(rowCount.toString()) - 1) / pageSize + 1;
            resMap.put("pageCount", pageCount);

        } catch (SQLGrammarException e) {
            e.printStackTrace();
            resMap.put("state", true);
            resMap.put("list", new LinkedList<>());
            resMap.put("pageCount", 1);
        } catch (Exception e) {
            e.printStackTrace();
            resMap.put("state", false);
            resMap.put("result", "数据库发生异常!");
        }

        return resMap;
    }

    /**
     * 根据提案的id,获取指定的提案,返回json对象
     * @return json
     */
    @ResponseBody
    @RequestMapping(value = "/{articleId}", method = RequestMethod.GET)
    public Map<String, Object> getArticleById(@PathVariable Integer articleId) {
        //TODO:权限管理
        Map<String, Object> resultMap = new LinkedHashMap<>();
        try {
            Article article = articleService.getArticleAndIncreaseClickCountById(articleId);
            resultMap.put("state", true);
            resultMap.put("article", article);
        } catch (Exception e) {
            resultMap.put("state", false);
            resultMap.put("result", "数据库错误!");
        }
        return resultMap;
    }

}
